# -*- coding: utf-8 -*-
"""
Created on Tue Jun  5 21:16:41 2018

@author: sun haiyang
"""
import os
import glob
from nilearn.input_data import NiftiMasker
import pandas as pd
from .linearcorrelation import Pearson_coeff,Spearman_coeff
from ..plot import Boxplot
from ..origin import Basic_str

#%%

class Across_voxel_correlate(Basic_str):
    #作用原理：for instance:对30个subject PET_z CBF_z做cross voxel analysis，and store the result as excel and picture
    #参数说明：
    #参数说明：
    #返回值说明：
    #举例：
    #调用：
    #被调用：
    #bug：
    def __init__(self,input_list,column_name_list,item):
        print('in the Volume_spatial_correlate')
        print('input_list:',input_list)
        #test if the input_list has four parameters
        if len(input_list) != 4 :
            raise Exception("the number of elements of input_list is not equal to 4")
        self.initialize_parameters(input_list,column_name_list,item)
        self.spatial_correlate()
        
    def initialize_parameters(self,input_list,column_name_list,item):
        

        ##########################################################################重新整理传入参数
        self.group1_dirpath = input_list[0]
        self.group2_dirpath = input_list[1]
        self.mask_dirpath = input_list[2]
        self.column_name_list = column_name_list
        self.tag = item
        
        self.GM_probability = os.path.split(os.path.split(self.mask_dirpath)[0])[1]
        self.region = os.path.split(self.mask_dirpath)[1]
        
        print('os.sep:',self.os_sep)
        print('search_path:',self.group1_dirpath+self.os_sep+self.star_suffix) 
        print('search_path:',self.group2_dirpath+self.os_sep+self.star_suffix)
        self.group1_filepaths = glob.glob(self.group1_dirpath+self.os_sep+self.star_suffix)
        self.group2_filepaths = glob.glob(self.group2_dirpath+self.os_sep+self.star_suffix)
        self.group1_filepaths.sort()
        self.group2_filepaths.sort()
        print('group1_filepaths:',self.group1_filepaths)
        print('group2_filepaths:',self.group2_filepaths)
        if len(self.group1_filepaths) != len(self.group2_filepaths):
            raise Exception("the number of file of group1 is different from that of group2 ")
        self.fileamount = len(self.group1_filepaths)
        self.group_correlation = pd.DataFrame(columns=self.column_name_list)
        
    def spatial_correlate(self):
          mask_filepaths = glob.glob(self.mask_dirpath+os.sep+self.star_suffix)
          mask_filepaths.sort()
          print('in saptial_correlate')
          for i in range(0,self.fileamount):
              print('iiiiiiiiiiiiiiii:',i)
              print('mask_filepath:',mask_filepaths[i])
              groupmask = NiftiMasker(mask_img=mask_filepaths[i])
              
              print('self.group1_filepath:',self.group1_filepaths[i])
              print('self.group2_filepath:',self.group2_filepaths[i])
              subjectID = self.get_subjectID(self.group1_filepaths[i])
              
              group1file_masked = groupmask.fit_transform(self.group1_filepaths[i])
              group2file_masked = groupmask.fit_transform(self.group2_filepaths[i])
#              group1file_masked = (group1file_masked - group1file_masked.mean())/group1file_masked.std()
#              group2file_masked = (group2file_masked - group2file_masked.mean())/group2file_masked.std()
              
              pcoeff = Pearson_coeff(group1file_masked.flatten(),group2file_masked.flatten())
              scoeff = Spearman_coeff(group1file_masked.flatten(),group2file_masked.flatten())
              
              
              
              
              #medi的意义仅仅代表这是一个中间变量,用于收集Pearson_coeff、Spearman_coeff
              #得到的相关系数以及其他必要的信息，然后放到
              medi = [group1file_masked.mean(),group2file_masked.mean()] + pcoeff.coeff_pvalue + [pcoeff.coeff_z] + \
                     scoeff.coeff_pvalue + [scoeff.coeff_z]
              medi = medi + [len(group1file_masked.flatten()),subjectID,self.tag,self.region,self.GM_probability]
              print('medi_after_append:',medi)
              
              #下面medi内的内容放到self.group_correlation中
              self.group_correlation = self.group_correlation.append(dict(zip(self.column_name_list,medi)),ignore_index=True)
              print('self.group_correlation:\n',self.group_correlation)

    def get_subjectID(self,filepath):
      agent_list = os.path.split(filepath)[1].split('_')
      subj_index = agent_list.index(self.subj_str)
      print('subj_index:',subj_index)
      subjectID = self.subj_str + self.underline + agent_list[subj_index + 1]
      print('subjectID:',subjectID)
      return  subjectID
#%%
class Multi_across_voxel_correlate(Basic_str):
    #作用原理：do all kinds of permutation and  use a for-loop to pass them to Volume_spatial_correlate  
    #参数说明：
    #参数说明：
    #返回值说明：
    #举例：
    #调用：
    #被调用：
    #bug：
    def __init__(self,input_list):
        #get the input_list
        if len(input_list) != 2 :
            raise Exception("the number of elements of input_list is not equal to 2")
        grouppath_dict = input_list[0]
        column_name_list = input_list[1]
        coeff_pvalue_df = pd.DataFrame(columns=column_name_list)
        #the other parameters
        x = 2
        y = 0
        special_str = r'across_voxel_correlate'
        excel_suffix = '.xlsx' 
        graph_suffix = '.png'
        coeff_pvalue_file_str = os.sep + special_str + excel_suffix
        ms_file_str = os.sep + 'mms_' + special_str + excel_suffix   #ms表示mean  std
        graph_filename = special_str + graph_suffix
        
        #begin to caculate
        for item in grouppath_dict.keys():
            print('item:',item)
            print('grouppath_dict[item]:',grouppath_dict[item])
            output_dirpath = grouppath_dict[item][3]
            gray_threshold_mask_dirpaths = glob.glob(grouppath_dict[item][2]+os.sep+self.star)
            print('gray_threshold_mask_dirpaths:',gray_threshold_mask_dirpaths)
            #之所以使用后面2重for循环，是因为r'/media/root/Elements4/XuanWu_dpabi_spm/mask/intersect_mask'这个文件夹的结构。
            for gray_threshold_mask_dirpath in gray_threshold_mask_dirpaths:
                region_mask_dirpaths = glob.glob(gray_threshold_mask_dirpath+os.sep+self.star)
                for region_mask_dirpath in region_mask_dirpaths:
                    grouppath_dict[item][2] = region_mask_dirpath
                    outcome = Across_voxel_correlate(grouppath_dict[item],column_name_list,item)
                    coeff_pvalue_df = coeff_pvalue_df.append(outcome.group_correlation,ignore_index=True)
        print('coeff_pvalue_df:',coeff_pvalue_df)
        
        #将coeff_pvalue_df存到一个csv文件里
        coeff_pvalue_df.to_excel(output_dirpath+coeff_pvalue_file_str)
        #求mean std,放在一个DataFrame中，进而存到一个csv文件中
#        medi = coeff_pvalue_df.groupby(column_name_list[x],column_name_list[x+1]).agg(['mean','median','std'])
#        medi.to_excel(output_dirpath+ms_file_str,sheet_name='sheet1')
#        
#        #plot
#        Boxplot(coeff_pvalue_df,column_name_list,x,y,output_dirpath,graph_filename)


#%%